<template>
  <div class="app-container">
    <!-- 骨架屏 -->
    <mobile-skeleton 
      v-if="loading" 
      :showHeader="true"
      :showSearch="false"
      :showCards="false"
      :showTable="true"
      :tableColumns="3"
      :tableRows="5"
      :showPagination="false"
    />
    
    <template v-else>
      <el-row :gutter="10" class="test_header" type="flex" align="middle" justify="start">
        <el-col :span="1">
          <img :src="backImg" style="width: 25px; height: 25px; cursor: pointer; margin-left: 10px" @click="goBack" />
        </el-col>
        <el-col :span="23">
          <h3 :style="{ color: theme }">课程目录</h3>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24" class="app-container">
          <el-table :data="list" style="width: 100%" row-key="id" border>
            <el-table-column label="序号" min-width="40">
              <template slot-scope="scope">
                {{ (queryParams.page - 1) * queryParams.page_size + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="课程" prop="name"></el-table-column>
            <el-table-column label="所属分类">
              <template slot-scope="scope">
                {{ scope.row.category.name }}
              </template>
            </el-table-column>
            <el-table-column label="完成情况">
              <template slot-scope="scope">
                <span v-if="scope.row.is_passed == true" :style="{ color: theme }">已完成</span>
                <span v-else style="color: red">未完成</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" :style="{
                  backgroundColor: theme,
                  borderColor: theme,
                  fontWeight: 'bold'
                }" @click="handlePre(scope.row)">学习</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </template>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import backImg from "@/assets/images/back.png";
import {
  trainDetail,
  TrainKnowledgeRecord,
} from "@/api/vadmin/train/train";
import {
  categoryDetail,
  knowledgeList,
} from "@/api/vadmin/course/course";
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
  name: "trainTest",
  components: { MobileSkeleton },
  data() {
    return {
      backImg: backImg,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      list: [],
      form: {},
      queryParams: {
        page: 1,
        page_size: 10,
      },
      defaultProps: {
        children: "children",
        label: "name",
      },
      courseId: "",
      courseOptions: [],
      trainId: this.$route.params.id || sessionStorage.getItem("trainId"),
      trainTaskId: this.$route.params.trainTaskId || sessionStorage.getItem("TrainTaskId"),
      isMobile: false,
      screenWidth: document.body.clientWidth,
      mediaQueryList: null
    };
  },
  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTreeselect();
    // 初始化移动设备状态
    this.isMobile = document.body.clientWidth < 768;
    // 监听屏幕宽度变化
    this.mediaQueryList = window.matchMedia("(max-width: 768px)");
    this.mediaQueryList.addListener(this.handleScreenWidthChange);
  },
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
    // 移除监听器
    if (this.mediaQueryList) {
      this.mediaQueryList.removeListener(this.handleScreenWidthChange);
    }
  },
  methods: {
    /** 查询菜单列表 */
    getList(id) {
      this.loading = true;
      knowledgeList({ category: id, page: 1, page_size: 1000 }).then((response) => {
        if (response && response.results) {
          this.list = response.results;
          this.getTrainKnowledgeRecord();
        } else {
          console.error("获取知识点列表返回的数据格式不正确:", response);
          this.list = [];
          this.loading = false;
        }
      }).catch(error => {
        console.error("获取知识点列表失败:", error);
        this.list = [];
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      trainDetail(this.trainId).then((res) => {
        // this.courseOptions.push(res.course);
        if (res && res.course && res.course.id) {
        this.courseId = res.course.id;
        categoryDetail(res.course.id).then((res) => {
            if (res) {
          this.courseOptions.push(res);
            }
          }).catch(error => {
            console.error("获取分类详情失败:", error);
        });
        this.getList(this.courseId);
        } else {
          console.error("获取培训详情失败:", res);
        }
      }).catch(error => {
        console.error("获取培训详情失败:", error);
      });
    },
    
    getTrainKnowledgeRecord() {
      const params = {
        train: this.trainId,
        page: 1,
        page_size: 10000,
      };
      TrainKnowledgeRecord(params).then((res) => {
        // console.log("完成情况", res);
        if (res && res.results) {
        const passedList = res.results;
        this.list.forEach((list) => {
          passedList.forEach((passedList) => {
            if (
              list["id"] == passedList["knowledge"]["id"] &&
              passedList["is_passed"] == true
            ) {
              this.$set(list, "is_passed", true);
            }
          });
        });
        }
      }).catch(error => {
        console.error("获取培训知识点记录失败:", error);
      });
      this.loading = false;
    },
    
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    
    goBack() {
      this.$router.push({ name: "train" });
    },
    
    // 移动端方法
    handleScreenWidthChange(e) {
      this.screenWidth = document.body.clientWidth;
      this.isMobile = this.screenWidth < 768;
    },
    
    /** 去培训 */
    handlePre(row) {
      this.$router.push({
        name: "Learning",
        params: { id: this.trainId, trainTaskId: this.trainTaskId, knowledgeId: row.id },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  .el-table {
    margin-top: 20px;
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .test_header {
    padding: 10px 0;
    
    h3 {
      font-size: 18px;
      margin: 0;
    }
  }
  
  .el-table {
    font-size: 14px;
  }
}
</style>